package xiangmu.schoolpaper.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xiangmu.schoolpaper.mapper.system.UpdateSystemWeightMapper;
import xiangmu.schoolpaper.pojo.DTO.UpdateSystemWeightDTO;
import xiangmu.schoolpaper.pojo.VO.WeightItemVO;
import xiangmu.schoolpaper.service.system.UpdateSystemWeightService;
@Service
public class UpdateSystemWeightServiceImpl implements UpdateSystemWeightService {
@Autowired
private UpdateSystemWeightMapper updateSystemWeightMapper;


    @Override
    @Transactional  // 事务注解：确保所有更新要么同时成功，要么同时失败
    public boolean updateSystemWeight(UpdateSystemWeightDTO updateSystemWeightDTO) {
        // 1. 参数校验
        if (updateSystemWeightDTO == null || updateSystemWeightDTO.getTemplateId() == null) {
            return false;  // 模板ID为空，更新失败
        }

        // 2. 获取权重列表
        java.util.List<WeightItemVO> weightList = updateSystemWeightDTO.getWeights();
        if (weightList == null || weightList.isEmpty()) {
            return false;  // 权重列表为空，无需更新
        }

        // 3. 遍历更新每个要素的权重
        for (WeightItemVO item : weightList) {
            // 3.1 绑定模板ID（确保要素与模板关联）
            updateSystemWeightDTO.setTemplateId(updateSystemWeightDTO.getTemplateId());

            // 3.2 执行更新操作（传入单个要素信息而非整个DTO）
            int affectedRows = updateSystemWeightMapper.updateSystemWeight(item);

            // 3.3 检查更新是否成功（如果有一条失败，整体回滚）
            if (affectedRows <= 0) {
                throw new RuntimeException("更新要素权重失败：" + item.getFactorId());
            }
        }

        // 4. 所有更新成功
        return true;
    }
}
